<template>
  <div class="file-preview-main" :class="{ inline: inline }">
    <div class="close" @click="close"><Icon :size="20" icon="material-symbols:close" /></div>
    <div :class="{ hidden }">
      <div class="file-preview-container">
        <div v-show="loading" class="well loading">正在加载中，请耐心等待...</div>
        <div v-show="!loading" class="well" ref="output"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { getExtend, readBuffer, render } from '@/vendors/util'
import axios from 'axios'
import { Icon } from '@/components/Icon'

/**
 * 支持嵌入式显示，基于postMessage支持跨域
 * 示例代码：
 *
 */
export default {
  name: 'FilePreview',
  components: { Icon },
  props: {
    url: String,
    type: String,
    inline: Boolean
  },
  data() {
    return {
      // 加载状态跟踪
      loading: false,
      // 上个渲染实例
      last: null,
      // 隐藏头部，当基于消息机制渲染，将隐藏
      hidden: false
    }
  },
  computed: {
    fileUrl() {
      const urlstrs = window.location.href.match(new RegExp('[?&]' + 'url' + '=([^&/#]+)', 'i'))
      const url = this.url || (urlstrs[1] ? decodeURIComponent(urlstrs[1]) : '')
      return url.split(':').reverse()[0]
    }
  },
  watch: {
    fileUrl(val) {
      console.log(val)
      this.loadFileByUrl()
    }
  },
  mounted() {
    console.log('fileUrl==>', this.fileUrl)
    this.loadFileByUrl()
  },
  methods: {
    async loadFileByUrl() {
      this.loading = true
      const urlPaths = this.fileUrl.split('/')
      const fileName = urlPaths[urlPaths.length - 1]
      if (this.fileUrl) {
        axios
          .get(this.fileUrl, {
            responseType: 'blob'
          })
          .then((res) => {
            this.readFile(this.blobToFile(res.data, fileName))
          })
          .finally(() => {
            this.loading = false
          })
      }
    },
    blobToFile(blob, fileName) {
      // 获取Blob对象的类型
      const type = blob.type
      // 创建一个File对象
      const file = new File([blob], fileName, { type })
      return file
    },
    async readFile(file) {
      this.loading = true
      try {
        const arrayBuffer = await readBuffer(file)
        this.loading = false
        this.last = await this.displayResult(arrayBuffer, file)
        this.$nextTick(() => {
          this.$el.querySelectorAll('img').forEach((img) => {
            if (img.parentNode?.style?.height === '0px') {
              img.parentNode.style.height = 'auto'
            }
            if (img.parentNode?.style?.width === '0px') {
              img.parentNode.style.width = 'auto'
            }
          })
        })
      } catch (e) {
        console.error(e)
      } finally {
        this.loading = false
      }
    },
    displayResult(buffer, file) {
      // 取得文件名
      const { name } = file
      // 取得扩展名
      const extend = this.type || getExtend(name)
      // 输出目的地
      const { output } = this.$refs
      // 生成新的dom
      const node = document.createElement('div')
      // 添加孩子，防止vue实例替换dom元素
      if (this.last) {
        output.removeChild(this.last.$el)
        this.last.$destroy()
      }
      const child = output.appendChild(node)
      // 调用渲染方法进行渲染
      return new Promise((resolve, reject) =>
        render(buffer, extend, child).then(resolve).catch(reject)
      )
    },
    close() {
      this.$emit('close')
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less">
.file-preview-main {
  position: fixed;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
  z-index: 4000;
  overflow: auto;
  background: gray;

  &.inline {
    position: relative;
    width: 100%;
    height: 100%;

    .close {
      display: none;
    }
  }

  .close {
    position: fixed;
    right: 15px;
    top: 10px;
    font-size: 20px;
    cursor: pointer;
    z-index: 2100;
    background: #ccc;
    color: #fff;
    display: inline-block;
    width: 20px;
    height: 20px;
    line-height: 20px;
    text-align: center;
    border-radius: 100%;
  }
  .file-preview-container {
    .well {
      display: block;
      background-color: #f2f2f2;
      // border: 1px solid #ccc;
      width: 100%;
      height: 100%;
      overflow: auto;
    }

    .loading {
      text-align: center;
    }

    .messages .warning {
      color: #cc6600;
    }

    .pptx-wrapper {
      max-width: 1000px;
      margin: 0 auto;
    }

    img,
    video {
      max-width: unset;
      left: unset !important;
      top: unset !important;
    }
  }
}
.el-image-viewer__wrapper {
  z-index: 3001 !important;
}
</style>
